;(function(global){
	var getGeolocation = global.getGeolocation = function (cb) {
		var timeout,timeHandle;
		if(navigator.geolocation){
			navigator.geolocation.getCurrentPosition(function(position){
				var pos = {
					lat: position.coords.latitude,
					lon: position.coords.longitude
				};
				if(!timeout){
					cb(null, pos);
					if(timeHandle){
						clearTimeout(timeHandle);
						timeHandle = null;
					}
				}
			}, function(error){
				var errors = {
						1: 'Authorization fails', // permission denied
						2: 'Can\'t detect your location', //position unavailable
						3: 'Connection timeout' // timeout
				};
				if(!timeout){
					cb({code: error.code, message: errors[error.code]});
					if(timeHandle){
						clearTimeout(timeHandle);
						timeHandle = null;
					}
				}
			}, {
				enableHighAccuray: false	
			});	
			timeHandle = setTimeout(function(){
				cb({code: 4, message: 'timeout'});
				timeout = true;
				timeHandle = null;
			}, 5000);
		}else{
			cb({code:0,message:'no support'});	
		}	
	};
	
	var getCity = global.getCity = function(lon, lat, fn){
		qwest.get('/proxy', {
				api_path: '/other/lonlataddress',
				fields_version: '3.3',
				v: '3.0',
				lon: lon,
				lat: lat
			}, function(){
				
			})
			.then(function(xhr, response){
				var res = utils.json.decode(response);
				if(res && res.status == 'success'){
					var result = res.result;
					result.lon = lon;
					result.lat = lat;
					fn(null, result);
				}else{
					fn(utils.json.encode(response));		
				}
			})
			.catch(function(xhr, res, err ){
				fn(utils.json.encode(err));	
			})
			.complete(function(xhr,res){
				//console.log('request city complete');	
			});
	};
	var updatePosition = global.updatePosition = function(fn){
		getCity('', '', fn);
		/*
		getGeolocation(function(err, position){
			if(err){
				//utils.showMsg(err.code + ' ' + err.message, 5000);
				getCity('', '', fn);
			}else{
				getCity(position.lon, position.lat, fn);
			}	
		});
		*/
	};
	var correctPosition = global.correctPosition = function(){
		//utils.showMsg('update pos', 5000)
		updatePosition(function(err, result){
			if(err){
				//utils.showMsg(utils.json.encode(err), 5000);	
			}else{
				//utils.showMsg(utils.json.encode(result), 5000);
				if(!!result.lat && !!result.lon){
					Cookies.set('lon', result.lon)
						.set('lat', result.lat);
				}
				Cookies.set('city_id', result.city_id)
					.set('city', result.city)
					.set('city_pinyin', result.pinyin);
			}	
		});	
	};
})(typeof window !== 'undefined' ? window : this);
